package com.Maykk.Demo09;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * @ClassName: ServerDownload
 * @Description: TODO TCP 接收文件中的内容并输出
 * @Author: MaykkStar@163.com
 */
public class ServerDownload {
    static final int PORT = 9527;
    static final String PATH = "./";

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);

        Socket socket = serverSocket.accept();

        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // 读取文件命并做出处理
        String fileName = br.readLine();

        // 获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        // 循环生成新文件名，判断文件名是否可用
        do {
            fileName = createFileName() + suffixName;
        } while (new File(PATH + suffixName).exists());

        // 通过新文件名创建文件输出流
        BufferedWriter bwFile = new BufferedWriter(new FileWriter(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            bwFile.write(line);
            bwFile.newLine();
            bwFile.flush();
        } // 客户端不会把 null 写给服务器，所以会造成不会退出循环

        socket.shutdownInput();
        // 反馈给客户端
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("文件上传成功");
        bw.newLine();
        bw.flush();

        bw.close();
        serverSocket.close();
    }

    /**
     * 创建文件名
     *
     * @return 文件名
     */
    private static String createFileName() {
        String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNQPQRSTUVWXYZ1234567890";
        Random ran = new Random();
        String filename = "";
        for (int j = 0; j < 10; j++) {
            filename += charSet.charAt(ran.nextInt(charSet.length()));
        }
        return filename;
    }
}
